var Common = require('wy-Common');
cc.Class({
    extends: cc.Component,

    properties: {
        tagPrefab : cc.Prefab,
        movePrefab :cc.Prefab,
        panelMenu : require('PanelMenu'),
        pathEditor : require('PathEditor'),
        slider :cc.Slider,
        fileName : cc.EditBox,
        toggle: cc.Toggle
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.graphics = this.node.getComponent(cc.Graphics);
        this.menu = this.node
        this.pathEditor.points =[];
        this.player = cc.instantiate(this.movePrefab);
        this.node.addChild(this.player);
        this.centerTag = cc.instantiate(this.movePrefab);
        this.node.addChild(this.centerTag);
        // this.player.active = false;
        this.slider.node.active =false;

        
        this.graphics.clear();

        this.isGetCirclePoint = false;
        this.isControlTag = false;
        this.datas = [];

        this.actionPanel = this.node.getChildByName('actionlist');
        for(var i=0; i<this.actionPanel.children.length; i++){
            var chd = this.actionPanel.children[i];
            chd.active =false;
            Common.addButtonHandler(this,chd,'onClickAction',i);
        }
    },
    onClickAction(e,d){
        if(this.pathEditor.points.length > d+1){
            this.pathEditor.runClickAction(d+1);
            this.updateTag(d+1,3)
        }
    },


    onControlSlider(e){
        this.drawCicle1(e.progress);
    },

    updateTag(idx,tag){
        cc.log('isEnd',tag);
        if(this.pathEditor.points.length == 1){
            var self = this;
            return;
        }
        var p = this.pathEditor.points[idx]
        if(tag == 3){
            this.panelMenu.node.active = true;
            this.panelMenu.showSelect(this.pathEditor.points[this.controlIndex],this.onBtnSelect.bind(this),true);
            return;
        }
        if(tag == 2){
            this.viewAction();
            return;
        }
        if(idx == this.pathEditor.points.length - 1){
            this.controlIndex = idx;
            var data = this.datas[idx];
            if(!data || data.action == undefined){
                this.panelMenu.node.active = true;
                this.datas[idx] = {time:1,shun : true}
                this.panelMenu.showSelect(this.pathEditor.points[this.controlIndex],this.onBtnSelect.bind(this));
            } else if(data.action == 0){

            } else if(data.action == 1){
                this.initCircleData(idx);
                this.drawCicle1(this.slider.progress);
            }
        } else {
            this.updateAction(idx);
        }
        this.slider.node.active = false;
    },

    deleteTag(idx){

    },
    updateAction(){
        return;
    },


    drawCicle1(progress){
        var p1 = this.circleData.p1;
        var p2 = this.circleData.p2;
        var dx = p2.x - p1.x;
        var dy = p2.y - p1.y;
        var x = ((this.circleData.e.x-this.circleData.s.x)*progress+this.circleData.s.x)
        // var x = p1.x
        var y = this.circleData.k*x + this.circleData.b;

        var ppp = this.graphics.node.convertToNodeSpaceAR(cc.v2(x,y))
        this.centerTag.setPosition(ppp)

        this.graphics.clear();
        this.graphics.strokeColor = cc.color(255,0,0,255);
        this.graphics.fillColor = cc.color(255,0,0,255);

        var len = Math.floor(Math.sqrt((p1.x-x)*(p1.x-x) + (p1.y-y)*(p1.y-y)))
        // this.graphics.circle(x,y,len);
        var center = cc.v2(Math.floor(x),Math.floor(y))
        var start = this.findAngle(center,p1,true);
        var end = this.findAngle(center,p2,false);

        this.datas[this.controlIndex].center = center;
        this.datas[this.controlIndex].start = start;
        this.datas[this.controlIndex].end = end;
        this.datas[this.controlIndex].radius = len

        this.graphics.arc(center.x,center.y,len,-start,-end,!this.datas[this.controlIndex].shun);

        // this.graphics.moveTo(this.circleData.s.x,this.circleData.s.y);
        // this.graphics.lineTo(this.circleData.e.x,this.circleData.e.y);

        this.graphics.stroke();
    },

    drawCicle(type,center){
        var t1 = this.pathEditor.points[this.pathEditor.points.length-2];
        var t2 = this.pathEditor.points[this.pathEditor.points.length-1];
        var p1 = this.graphics.node.convertToNodeSpace(t1);
        var p2 = this.graphics.node.convertToNodeSpace(t2);
        var pc = this.graphics.node.convertToNodeSpace(center);

        this.graphics.clear();
        this.graphics.strokeColor = cc.color(255,0,0,255);
        this.graphics.fillColor = cc.color(255,0,0,255);

        this.graphics.moveTo(p1.x,p1.y);
        this.graphics.lineTo(pc.x,pc.y);
        this.graphics.lineTo(p2.x,p2.y);

        var cd = this.findCircle(p1,p2,pc);
        var start = this.findAngle(cd,p1,true);
        var end = this.findAngle(cd,p2,false);

        // y = kx+b

        var k = (p1.y-p2.y)/(p1.x-p2.x)
        var b = p2.y - k * p2.x 
        var cdy = cd.x*k+b;
        var centery = pc.x*k+b;
        
        var b = cdy > cd.y;
        var c1 = centery > pc.y
        var c = b ==c1

        var k1 = (cd.y-p2.y)/(cd.x-p2.x)
        cc.log('',k,k1,b)
        this.graphics.arc(cd.x,cd.y,cd.radius,-start,-end,c);

        var ppp = this.graphics.node.convertToNodeSpaceAR(cc.v2(cd.x,cd.y))
        this.centerTag.active = true;
        this.centerTag.setPosition(ppp)

        this.graphics.stroke();

        var pi = 180 / Math.PI

        if(type == cc.Node.EventType.TOUCH_END){
            
            var s1 = start
            var s2 = end
            this.player.active = true;
            this.player.stopAllActions();
            var sp = this.graphics.node.convertToNodeSpaceAR(this.pathEditor.points[this.pathEditor.points.length-2])  
            this.player.setPosition(sp);
            this.player.runAction(cc.repeatForever(cc.circle(0.5,ppp,cd.radius,s1+0.5*Math.PI,s2+0.5*Math.PI,true)));
        }
    },

    findAngle(p1,p2,sec){
        var np = p2.sub(p1);
        var a = cc.v2(0,0).signAngle(np);
        return  a
    },

    //根据圆上三点，计算圆的中心和半径
    findCircle(p1,p2,p3){
        var pt1 = cc.v2(0,0)
        var pt2 = cc.v2(0,0) 
        pt1.x = (p1.x+p2.x)/2
        pt1.y = (p1.y+p2.y)/2

        pt2.x = (p1.x+p3.x)/2
        pt2.y = (p1.y+p3.y)/2
        var k1 = (p2.y == p1.y ? 1 : -(p2.x-p1.x) / (p2.y-p1.y))
        var k2 = (p3.y == p1.y ? 1 : -(p3.x-p1.x) / (p3.y-p1.y))
        var centerx = (pt2.y - pt1.y - k2* pt2.x + k1*pt1.x) / (k1 - k2);
        var centery = pt1.y + k1*(pt2.y-pt1.y-k2*pt2.x + k2*pt1.x)/(k1-k2);
        var radius = Math.sqrt( (centerx-p1.x)*(centerx-p1.x) + (centery-p1.y)*(centery-p1.y))
        return {x:Math.floor(centerx),y:Math.floor(centery),radius:Math.floor(radius)}
    },

    onBtnSelect(action,time,delay){
        
        var p = this.pathEditor.points[this.controlIndex]

        this.datas[this.controlIndex].time = parseFloat(time);
        this.datas[this.controlIndex].delay = parseFloat(delay);
        this.datas[this.controlIndex].action = action
        if(action == 0){
            this.panelMenu.node.active = false;
            this.viewAction();
        } else if(action == 1){
            this.panelMenu.showEditor(this.datas[this.controlIndex].shun);
            this.initCircleData(this.controlIndex);
            this.slider.progress = 0;
            this.drawCicle1(0);
            this.isGetCirclePoint = true;
            this.slider.node.active =true;
        }
    },
    onBtnCicleFinish(){
        cc.log('onBtnCicleFinish');
        this.panelMenu.node.active = false;
        var data = this.datas[this.controlIndex];
        
        this.viewAction();
    },
    onToggleChange(t){
        cc.log('onToggleChange',t.toggle.getToggle())
        this.datas[this.controlIndex].shun = t.toggle.getToggle() == 0;
        this.drawCicle1(this.slider.progress)
        // this.datas[this.controlIndex].shun = 1
    },
    initCircleData(idx){
        var t1 = this.pathEditor.points[idx-1];
        var t2 = this.pathEditor.points[idx];
        var p1 = this.graphics.node.convertToNodeSpace(t1);
        var p2 = this.graphics.node.convertToNodeSpace(t2);
        var dx = Math.abs(p2.x-p1.x);
        var dy = Math.abs(p2.y-p1.y);
        var dl = Math.max(dx,dy);
        var sx = Math.min(p1.x,p2.x)-(dl-dx)/2
        var sy = Math.min(p1.y,p2.y)-(dl-dy)/2 
        var ex = Math.max(p1.x,p2.x)+(dl-dx)/2
        var ey = Math.max(p1.y,p2.y)+(dl-dy)/2

        this.centerTag.setPosition(cc.v2(0,0))
        var k  = p2.x == p1.x ? 1 : (p2.y-p1.y)/(p2.x-p1.x);
        cc.log('initCircleData:',p1,p2);
        cc.log(sx,sy,ex,ey)
        
        var k1 = -1 / k;
        var b1 = ((p2.y-p1.y)/2+p1.y) - k1 * ((p2.x-p1.x)/2+p1.x )
        this.circleData = {
            k : k1,
            b : b1,
            p1 : p1,
            p2 : p2,
            s:cc.v2(sx,sy),
            e :cc.v2(ex,ey)
        }
    },
    viewAction(){
        this.actionPanel = this.node.getChildByName('actionlist');
        for(var i=0; i<this.actionPanel.children.length; i++){
            var chd = this.actionPanel.children[i];
            chd.active = false;
        }

        var points = this.pathEditor.points;
        var actions = [];
        for(var k in this.datas){
            var data = this.datas[k];
            actions.push(cc.delayTime(data.delay));
            var no = this.actionPanel.getChildByName('item'+(k-1)).getComponent(cc.Label)
            no.node.active = true;
            if(data.action == 1){
                no.string = 'cir:c:'+data.center.x+','+data.center.y+',r:'+data.radius+',s:'+data.start.toFixed(2)+',e:'+data.end.toFixed(2)
                actions.push(cc.circle(data.time,data.center,data.radius,data.start+0.5*Math.PI,data.end+0.5*Math.PI,!data.shun))
            } else {
                no.string = 'move:'+points[k].x+','+points[k].y
                actions.push(cc.moveTo(data.time,points[k]));
            }
        }
        var self = this;
        if(actions){
            actions.splice(0,0,cc.callFunc(function(){
                self.player.setPosition(self.pathEditor.points[0])
            }))
            if(cc.sys.isNative){
                actions.push(cc.delayTime(0))
            }
        }
        this.centerTag.active = false;
        this.player.active = true;
        this.player.stopAllActions();
        this.player.setPosition(self.pathEditor.points[0])
        this.player.runAction(cc.repeatForever(cc.sequence(actions)));
    },

    onSaveFile(){
        cc.log('fileName:',this.fileName.string);
        var pathurl = "D:/PathList/outpath/"+this.fileName.string+".txt";
        var screen = cc.find('Canvas/view');

        var data = {
            points : [],
            datas : [],
            isRotation : Boolean
        }
        for(var i=0; i<this.pathEditor.points.length; i++){
            data.points.push(screen.convertToNodeSpaceAR(this.pathEditor.points[i]).scale(cc.v2(2, 2)))
        }
        for(var k in this.datas){
            var d = this.datas[k];
            data.datas[k] = {};
            Object.assign(data.datas[k],d);
            if(d && d.action == 1){
                data.datas[k].center = screen.convertToNodeSpaceAR(d.center).scale(cc.v2(2, 2))
                data.datas[k].radius *= 2;
            }
        }
        data.isRotation=this.toggle.isChecked;
        cc.log('data:',data);
        cc.log(JSON.stringify(data));
        
        if (cc.sys.isNative) {
            jsb.fileUtils.writeStringToFile(JSON.stringify(data),pathurl);
        }
    }

    // update (dt) {},
});
